<template>
  <div>
     <a-card>
      <div class="ui segment">
        <div class="table-operator buttons">
          <a-button @click="handleAdd" type="primary" ><FileAddOutlined />新单</a-button>
          <router-link to="/finance/excelImportData">
            <a-button type="primary"><UploadOutlined />导入</a-button>
          </router-link>
          <a-dropdown>
            <template #overlay>
              <a-menu class="ant-dropdown-link" @click="exportExcel">
                <a-menu-item key=0 >默认</a-menu-item>
                <template :key="v.id" v-for="v of templateFilter('Finance-checkbill')">
                  <a-menu-item>{{v.name}}</a-menu-item>
                </template>
              </a-menu>
            </template>
            <a-button type="primary" v-show="exportable"><DownloadOutlined />导出</a-button>
          </a-dropdown>
          <a-button type="primary" v-show="accountable" @click="handleCheck"><AccountBookOutlined />核对入帐</a-button>
          <a-button type="primary" v-show="invoiceable" @click="handleInvoice"><SnippetsOutlined />开票</a-button>
          <a-button @click="reset()" type="primary"><SearchOutlined />查询</a-button>
        </div>
      </div>
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper" v-show="searchable">
        <a-form :label-col="{ span: 7 }" :wrapper-col="{ span: 17 }">
          <!-- 第一行-->
          <a-row :gutter="16">
            <a-col :span="6">
              <a-form-item label="帐单日期">
                    <a-range-picker
                        allowClear
                        v-model:value="queryParams.bill_date"
                        :show-time="{ format: 'HH:mm:ss' }"
                        format="YYYY-MM-DD HH:mm:ss"
                        :ranges="dateRange"
                        value-format="YYYY-MM-DD HH:mm:ss"
                     />
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="帐单号">
                    <a-input allowClear v-model:value="queryParams.bill_no"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="贸易方">
                    <a-select allowClear  showSearch
                              :filter-option="false"
                              @search="(value) => searchTextForTraders=value"
                              :options="customizedFilterOptions(searchTextForTraders, checkBillStore.groupedTradePartners)"
                              @change="changePartner"
                              dropdownClassName="custom-dropdown"
                              v-model:value="queryParams.id_trade_partner">
                    </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="目的港">
                <a-select showSearch  allowClear  v-model:value="queryParams.destination_port">
                  <template v-for="i of checkBillStore.ports">
                    <a-select-option  :key="i.id" :value="i.code" v-if='i.port_type > 1' >
                      {{i.code}}
                    </a-select-option>
                  </template>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <!-- 第二行-->
          <a-row :gutter="16">
            <a-col :span="6">
                <a-form-item label="入帐公司">
                  <a-select allowClear v-model:value="queryParams.id_company" :options="checkBillStore.companies"/>
                </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="帐单状态">
                <a-select showArrow allowClear v-model:value="queryParams.status"
                          mode="multiple" @change="clearChoice"
                          :options="dictOpts.status.value">
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="客户"  >
                <a-select allowClear showSearch optionFilterProp="children"
                          :filter-option="false"
                          @search="(value) => searchTextForClients=value"
                          :options="customizedFilterOptions(searchTextForClients, checkBillStore.clients)"
                          v-model:value="queryParams.id_client">
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="分组统计">
                <a-select allowClear v-model:value="queryParams.group">
                  <a-select-option value="id_company">按入帐公司</a-select-option>
                  <a-select-option value="id_trade_partner">按贸易客户</a-select-option>
                  <a-select-option value="status">开票状态</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="2" :offset="1">
              <a-form-item>
                <a-button @click.prevent="search" :disabled="queryParams.disabled" type="default">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 查询区域-END -->
      <!-- table区域-begin -->
      <div>
        <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="group"
            :columns="columnsSummaryFiltered"
            :customHeaderRow="headerClick('checkingBillSummary', instance)"
            :rowClassName="setRowStyle()"
            :dataSource="dataSource"
            :pagination="false"
            :loading="loading"
        >
          <template #group="{text}">
            <span :class="{'underline': !text && text !==0 }">{{groupObj(text)}}</span>
          </template>
          <template #money="{text}">￥{{text||0}}</template>
        </a-table>
      </div>
      <div>
        <!--定义了scroll才能产生滚动效果-detail-->
        <a-table
            ref="tableDetail"
            size="small"
            bordered
            rowKey="id"
            :columns="columnExtra"
            :customHeaderRow="headerClick('checkingBillDetail', instance)"
            :dataSource="dataSourceDetail"
            :pagination="ipagination"
            :rowSelection="rowSelection()"
            @change="handleTableChange"
            :scroll="scroll()"
            :loading="loading"
        >
          <template #total_amount="{ text, record }">
            <a-tooltip :class="{'ant-table-row-selected rowBeExec': !queryParams.id_trade_partner}" placement="left" :title="feeTip(record)" :get-popup-container="getPopupContainer">
              <span>{{text}}</span>
            </a-tooltip>
          </template>
          <template #company="{text:t}">{{(checkBillStore.companyObj[t]||'')}}</template>
          <template #tradePartner="{text:t}"><span v-html="checkBillStore.tradePartnerObj[t] && (checkBillStore.tradePartnerObj[t].fullname||'')"></span></template>
          <template #action="{text, record}">
            <span>
              <a  @click.prevent="handleEdit(record)">编辑</a>
              <a-divider type="vertical"/>
              <a-dropdown>
                <a class="ant-dropdown-link" @click.prevent>更多<DownOutlined /></a>
                <template #overlay>
                      <a-menu>
                        <a-menu-item  @click="view(record)">
                          详细
                        </a-menu-item>
                        <a-menu-item v-if="record.status<1">
                          <a-popconfirm title="是否确认删除吗?" ok-text="是" cancel-text="否"  @confirm="() => del(record)">
                            <a>删除</a>
                          </a-popconfirm>
                        </a-menu-item>
                      </a-menu>
                </template>
              </a-dropdown>
            </span>
          </template>
        </a-table>
      </div>
   </a-card>

     <DetailModal ref="detailModal" size="small" :dictProperties="checkBillStore.dictObj" :columns="columnsTmp" @toEdit="handleEdit" infoName="对帐单明细"></DetailModal>
     <BillAddModal ref="addModal" @sync="updateMain" :ports="checkBillStore.ports" :feeTypeById="checkBillStore.feeTypeById" size="small" :url = "url" :isAdmin="currentUser.isAdmin"
                   :dictProperties="checkBillStore.dictObj" :tradeObj="checkBillStore.groupedTradePartners" :tradePartners="checkBillStore.tradePartners" :companies="checkBillStore.companies"></BillAddModal>
     <BillCheckedDrawer ref="checkDrawer" @close="search" :clients="checkBillStore.clients" :companies="checkBillStore.companies" @sync="updateBillStatus" ></BillCheckedDrawer>
     <BillInvoiceDrawer ref="invoice" @close="search" :clients="checkBillStore.clients" :companies="checkBillStore.companies" @sync="updateBillStatus" ></BillInvoiceDrawer>
     <ColumnConfigDrawer :visible="columnCfgVisible" @close="columnConfigClose" :keyId="columnConfigKey"
                         @update:data="onColumnsUpdate" :originalConfigData="originalConfigData" :currentConfigData="currentConfigData"/>
  </div>
</template>


<script setup>
import { ref, reactive, toRefs, nextTick } from 'vue';
import useCheckBillStore from "@/store/modules/checkBill.js";
import BillAddModal from '@/views/modules/BillAddModal.vue'
import BillCheckedDrawer from '@/views/modules/BillCheckedDrawer'
import BillInvoiceDrawer from '@/views/modules/BillInvoiceDrawer'
import DetailModal from "@/views/modules/basicModal/DetailModal.vue";
import ColumnConfigDrawer from '@/views/modules/basicDrawer/ColumnConfigDrawer.vue'
import {
  accAdd, accMinus, commonConf, filterColumns, headerClick,
  customizedFilterOptions, handleExportXls, columnsMerge
} from '@/utils/my';
import moment from "moment";
import _ from 'lodash'
import { postAction, getAction, deleteAction } from '@/utils/request'
import dayjs from 'dayjs';
import useUserStore from '@/store/modules/user'
import { useRoute } from 'vue-router'

// 按需引入组件
import { Button, Card, Row, Col, Form, FormItem, Select, SelectOption,
         Table, Modal, message, DropdownButton, Dropdown } from 'ant-design-vue';
// 手动注册组件
const AButton = Button, ASelect = Select, ASelectOption = Select, AModal = Modal;
const AForm = Form, AFormItem = FormItem, ATable = Table, ADropdownButton = DropdownButton, ADropdown = Dropdown;
const ACard = Card, ARow = Row, ACol = Col;

const currentUser = useUserStore()
const route = useRoute()
//store
// 获取 userStore 实例
const checkBillStore = useCheckBillStore()
checkBillStore.getPortsAndClient()
checkBillStore.getTradePartner()
checkBillStore.getFeeTypes()
checkBillStore.getMyCompanies()
checkBillStore.getColumnSettings(["checkingBillDetail","checkingBillSummary"])
// inject
//const currentUser = inject('currentUser', false)

// Data
const originalConfigData = ref([])
const currentConfigData = ref([])
const columnCfgVisible = ref(false)
const columnConfigKey = ref("checkingBillDetail")
const instance = getCurrentInstance();
const proxy = instance.proxy
const dictOpts = proxy.useDict("status","client_group","bill_type");
const loading = ref(false);
const searchable = ref(false);
const exportable = ref(false);
const table = reactive({
      selectedRowKeys: [],
      selectionRows: []
})
const searchText = ref('')
const templates = ref([])
const feeColumns = ref([])
const feeTipStr = ref({})
const searchTextForClients = ref('')
const searchTextForTraders = ref('')

////reactive+refs
const data = reactive({
  queryParams: {
    bill_date: [],
    id_company: undefined,
    id_trade_partner: undefined,
    bill_no: undefined,
    status: undefined,
    group: undefined,
    id_client: undefined,
    destination_port: undefined,
    disabled: false
  },
  ipagination: commonConf("ipagination")
});
const { queryParams, ipagination} = toRefs(data);
const dataSourceDetail = ref([])
const dataSource = ref([])
const columnsTmp = ref([])
////模板引用
const detailModal = ref(null);
const addModal = ref(null);

// simple vars
const diction =  checkBillStore.dictObj
const dateRange = {
  '今天': [dayjs().startOf('day'), dayjs().endOf('day')],
  '昨天': [dayjs().subtract(1, 'day').startOf('day'), dayjs().subtract(1, 'day').endOf('day')],
  '最近7天': [dayjs().subtract(6, 'day').startOf('day'), dayjs().endOf('day')],
  '本月': [dayjs().startOf('month'), dayjs().endOf('month')],
  '上月': [dayjs().subtract(1, 'month').startOf('month'), dayjs().subtract(1, 'month').endOf('month')],
  "近三个月": [dayjs().subtract(3, 'month').startOf('month'), dayjs().subtract(1, 'month').endOf('month')],
};
const url = {
  getCheckBills: '/yg/finance/getCheckBill',
  saveCheckBill: '/yg/finance/saveCheckBill',
  delCheckBill: '/yg/finance/delCheckBill',
  getDataBySql: '/sys/getDataBySql',
  asyncDataBySql: '/sys/asyncDataBySql',
  template: '/yg/template',
  exportXlsForCheckBills: '/yg/exportXlsForCheckBills',
}

//// 表头
const columnsSummary =[
  {
    title: '统计分组', align: 'center', dataIndex: "group", width: 250,
    slots: { customRender: 'group' }
  }, {
    title: '记录数', align: 'right', dataIndex: 'total', width: 180
  }, {
    title: '收入', align: 'right', dataIndex: 'income',
    slots: { customRender: 'money' }
  }, {
    title: '支出', align: 'right', dataIndex: 'expenditure',
    slots: { customRender: 'money' }
  }, {
    title: '利润', align: 'right', dataIndex: 'profit',
    customRender: function({text, record, index}) {
      let income = record.income||0
      let expenditure = record.expenditure||0
      return "￥"+_.round(_.add(income,-expenditure),2)
    }
  }
]

const columnsDetail = [
  {
    title: '#', key: 'rowIndex', width: 30, align: 'center', fixed: 'left',
    customRender: function({text, record, index}) {
      return parseInt(index) + 1
    }
  },{
    title: '帐单日期', align: 'center', width: 90, sorter: true, dataIndex: 'bill_date',
    customRender: function({text, record, index}) {
      return text && moment(text).format("YYYY-MM-DD")
    }
  },{
    title: '贸易方', align: 'center', width: 80, dataIndex: 'id_trade_partner',
    slots: { customRender: 'tradePartner' }
  },{
    title: '帐单类型', align: 'center', width: 40, dataIndex: 'bill_type',
  },{
    title: '帐单号', align: 'center', width: 110, dataIndex: 'bill_no',
  },{
    title: '航班号', align: 'center', width: 70, dataIndex: 'flight_no',
  },{
    title: '始发港', align: 'center', width: 60, dataIndex: 'departure_port',
    customRender: function({text}) {
      return text || 'HGH'
    }
  },{
    title: '目的港', align: 'center', width: 60, dataIndex: 'destination_port',
  },{
    title: '件数', align: 'center', width: 70, dataIndex: 'articles',
  },{
    title: '重量', align: 'center', width: 70, dataIndex: 'weight',
  },{
    title: '计费重量', align: 'center', width: 70, dataIndex: 'weight_for_fee',
  },{
    title: '单价', align: 'center', width: 60, dataIndex: 'unit_price',
  },{
    title: '总金额', align: 'right', width: 75, sorter: true, dataIndex: 'total_amount',
    slots: { customRender: 'total_amount' }
  },{
    title: '入帐公司', align: 'center', width: 120, dataIndex: 'id_company',
    slots: { customRender: 'company' }
  },{
    title: '状态', align: 'center', width: 60, dataIndex: 'status', //用自动生成的customRender
    // customRender: function({text}) {
    //   return checkBillStore.dictObj.status[text] || text
    // }
  },{
    title: '备注', align: 'center', width: 120, dataIndex: 'memo',
  },{
    title: '操作', align: 'center', dataIndex: 'action', width: 120, fixed: 'right',
    slots: { customRender: 'action' }
  }
]

// computed
const selectable = computed(() => {
  return queryParams.value.id_trade_partner ||
      (queryParams.value.id_client && queryParams.value.status && queryParams.value.id_company);
});
const accountable = computed(() => {
  return selectable.value &&
      queryParams.value.status &&
      queryParams.value.status.join('') === '0';
});
const invoiceable = computed(() => {
  return selectable.value &&
      queryParams.value.status &&
      queryParams.value.status.join('') === '1';
});
const templatesDict = computed(() => {
  let obj = {}
  templates.value.forEach((c)=> obj[c.id] = c)
  return obj;
})
const columnsDetailFinal = ref([])
const columnsSummaryFinal = ref([])
const columnsDetailTmp = ref([])
const columnsSummaryTmp= ref([])
watchEffect(()=>{
  // 基础配置合并在数据库里的配置－>最终配置;解决遗漏配置和少customRender问题
  columnsDetailFinal.value = columnsMerge(columnsDetailTmp.value, checkBillStore.dictObj.checkingBillDetail, columnsDetail)
  columnsSummaryFinal.value = columnsMerge(columnsSummaryTmp.value, checkBillStore.dictObj.checkingBillSummary, columnsSummary)
})
// console.error("columnsDetailFinal:", JSON.stringify(columnsDetailFinal.value))
const columnExtra = computed(() => {
  // console.error("checkBillStore.dictObj.checkingBillDetail:", JSON.stringify(checkBillStore.dictObj.checkingBillDetail))
  // 字段之间插入进来
  const baseColumns = columnsDetailFinal.value.filter((c)=> !(c.visible === false))
  let index_start = baseColumns.findIndex((c)=>{return c.dataIndex==='unit_price'}) + 1
  let index_end = baseColumns.findIndex((c)=>{return c.dataIndex==='total_amount'})
  // 指定位置加明细项
  baseColumns.splice(index_start,index_end-index_start,...feeColumns.value)
  // 用到value2text; 会修改column原数据,即：根据字典添加customRender,如果没有customRender
  return filterColumns(baseColumns)
})
const columnsSummaryFiltered = computed(() => {
  return filterColumns(columnsSummaryFinal.value)
})
// Watch
// watch(
//     [
//       () => queryParams.bill_date,
//       () => queryParams.group
//     ],
//     _.debounce((newValues, oldValues) => {
//       dataSource.value = [];
//       dataSourceDetail.value = [];
//     }, 300),
//     { deep: true }
// );

// methods
const columnConfigClose = () => {
      columnCfgVisible.value = false
      //queryList()
}

const autoQuery = () =>{
      // 变换url传参，触发查询
      let newBillNo = route.query.billNo, newTimestamp = route.query.timestamp
      if (newBillNo !== undefined) {
        console.log('billNo changed:', newBillNo)
        queryParams.value.bill_no = newBillNo
        queryList()
      }
      if (newTimestamp !== undefined) {
        console.log('timestamp changed:', newTimestamp)
        queryList()
      }
}
//// 处理搜索输入
const handleFilter = (value) => {
  searchText.value = value.toLowerCase();
};

function reset(){
  searchable.value =! searchable.value
  queryParams.value = {
        bill_date: [],
        id_company: undefined,
        id_trade_partner: undefined,
        bill_no: undefined,
        status: undefined,
        group: undefined,
        id_client: undefined,
        port: undefined,
        disabled: false
  }
  dataSource.value = [];
  dataSourceDetail.value = [];
  feeColumns.value =[]
  ipagination.value = commonConf("ipagination")
}
async function handleAdd() {
  await nextTick(()=>{
    addModal.value.add();
  })
}

function handleEdit(record) {
  if(record.status > 0) {
      message.error(`${record.bill_no}已入帐，不能修改！`)
      return
  }
  proxy.$refs.addModal.edit(record);
}

function exportExcel(e){
  //验证
  if(!dataSourceDetail.value || dataSourceDetail.value.length === 0){
    message.error({content: "没有要导出的数据！"}); return
  }
  if(!queryParams.value.id_trade_partner){
    message.error({content: "请选择贸易方！"}); return;
  }
  //参数及调用
  let timeStamp = moment().format("YYYYMMDDmmHHSS")
  let today = moment().format("YYYY-MM-DD")
  let partner = checkBillStore.tradePartnerObj[queryParams.value.id_trade_partner]
  let id_company = queryParams.value.id_company || partner.id_company
  let myCompanyInfo = checkBillStore.companyObj[id_company]
  let title = partner.title+'对帐单';
  let subtitle = `制表人： ${currentUser.name}   日期：${today}   `;
  if (myCompanyInfo && myCompanyInfo.memo) subtitle += myCompanyInfo.memo
  let sheetName = `${title}-${today}`;
  let fileName = `${title}-${timeStamp}`;
  let columnExceptions = ['id', 'id_company', 'id_trade_partner', 'bill_type']
  let columns = columnExtra.value.filter(c=>{
    return columnExceptions.indexOf(c.dataIndex) === -1 && c.is_show !== 0 && c.title !== '#'
  }).map((c)=>{
    return _.pick(c,['title','width','dataIndex'])
  })
  let exportConfig = templatesDict.value[e.key] ? JSON.parse(templatesDict.value[e.key].config):{}
  let searchConditions = { ...queryParams.value, ids: table.selectedRowKeys }
  let params = {
    fileName, sheetName, title, subtitle, columns, exportConfig, searchConditions, dictOptions: diction,
  }
  console.log("params：", params)
  handleExportXls(url.exportXlsForCheckBills, params)
}

function getTemplateConfig(){
  getAction(url.template, {category: 'json'}).then(res => {
    if (res && res.success && _.isArray(res.data)) {
        templates.value = res.data
    }
  })
}

function templateFilter(template_type){
  return templates.value.filter((t) => t.template_type && t.template_type.code === template_type)
}

function audit(type){
  if(table.selectedRowKeys.length === 0) {
    message.error({content: `请选要${type}的记录！`})
    return
  }
  let param = Object.assign({},queryParams.value)
  let partner = param.id_trade_partner && checkBillStore.tradePartnerObj[param.id_trade_partner]
  if(partner && !param.id_client) param.id_client = partner.id_client; param.id_trade_partner = partner.id
  if(partner && !param.id_company) param.id_company = partner.id_company
  let total  = {}
  if(table.selectionRows.length > 0){
    let income = 0, expenditure = 0
    table.selectionRows.forEach( (d) =>{
      if(d.bill_type === 1)
        income = accAdd(income, d.total_amount)
      else
        expenditure = accAdd(expenditure, d.total_amount)
    })
    total.total = table.selectionRows.length;
    total.income = income; total.expenditure=expenditure;
  }
  if(total) Object.assign(param,total)
  param.profit = accMinus(param.income||0,param.expenditure);
  if (type === "入帐") param.id_checked_bills = table.selectedRowKeys
  else param.id_invoiced_bills = table.selectedRowKeys
  param.update_by = currentUser.name
  return param
}

function handleCheck(){
  let param = audit("入帐")
  if(param)
    proxy.$refs.checkDrawer.showBillToCheck(param);
}

function handleInvoice(){
  let param = audit("开票")
  if(param)
    proxy.$refs.invoice.showBillToVoice(param);
}

function scroll(){
  let length = 1270
  if(queryParams.value.id_trade_partner) {
    feeColumns.value.forEach((fc)=>{
      length += parseInt(fc.width)
    })
    length += 50
  }
  return {x: length}
}

const changeColumnConfig = (keyId) => {
  columnConfigKey.value = keyId
  if(keyId === "checkingBillDetail"){
    originalConfigData.value = columnsDetail
    currentConfigData.value = columnsDetailFinal.value
  }else if(keyId === "checkingBillSummary"){
    originalConfigData.value = columnsSummary
    currentConfigData.value = columnsSummaryFinal.value
  }
  //console.error("columnsSummaryFiltered:", JSON.stringify(columnsSummaryFiltered.value))
  columnCfgVisible.value = true
}

function changePartner(value){
  dataSourceDetail.value = [];dataSource.value = [];queryParams.value.id_company = undefined;
  if(value)  exportable.value = true;
  let partner = checkBillStore.tradePartnerObj[value]
  let fee_items = partner && partner.fee_items.split(",")
  if(fee_items){
      feeColumns.value = []
      fee_items.forEach(f=>{
          feeColumns.value.push( {
            title: checkBillStore.feeTypeById[f].label,
            align: 'center',
            width: 65,
            dataIndex: checkBillStore.feeTypeById[f].value,
            is_show: 1,
            customRender: ({ text }) => {
              return text || 0;
            },
          })
      })
  }
  if(partner){
      queryParams.value.id_client = partner.id_client
      queryParams.value.id_company = partner.id_company
      // console.error("queryParams:",JSON.stringify(queryParams.value))
  }
}

function feeTip(r) {
  feeTipStr.value[r.id] || parseFeeDetail(r)
  if (!queryParams.value.id_trade_partner)
        return feeTipStr.value[r.id] || "无";
}

function getPopupContainer(trigger) {
  return trigger.parentElement;
}

function groupObj(v){
  if((v === undefined) || (v === null)) return '合 计';
  switch(queryParams.value.group){
    case 'id_trade_partner':
      return checkBillStore.tradePartnerObj[v].name? `${checkBillStore.tradePartnerObj[v].group_type}-${checkBillStore.tradePartnerObj[v].name}` : v;
    case 'id_company':
      return checkBillStore.companyObj && checkBillStore.companyObj[v]||v;
    case 'status':
      return checkBillStore.dictObj.status[`${v}`]||v;
    default:
      return "合 计";
  }
}

function del(record){
  deleteAction(url.delCheckBill, {},{ids:[record.id]}).then((res)=>{
      if (res.success) {
        message.success("删除成功")
        queryList();
      } else {
        message.error(`删除除失败!${res.message}`)
        console.error('错误原因', res.message)
      }
    })
}
//feeData从子组context拿
async function edit(record){
  // parseFeeDetail(record);
  //console.log(JSON.stringify(record.feeData))
  handleEdit(record)
}
//feeData从record拿
async function view(record){
  //分次复制，以便保持顺序, 决定顺序
  let orderArr = ['bill_no','bill_date','bill_type','flight_no','id_trade_partner',
    'departure_port','destination_port','articles', 'weight','weight_for_fee','unit_price','status',
    ...Object.keys(record.feeData),'total_amount','id_company','id','memo','create_by','update_by',
    'create_time','update_time']
  //字段label
  let feeCols  = []
  if(record.feeData)
      for (let k in record.feeData){
          feeCols.push( {
              title: record.feeData[k].name,
              dataIndex: record.feeData[k].code,
              is_show: 1
          })
      }
  console.log("feeCols:"+JSON.stringify(feeCols))
  console.log("columnsDetail:"+JSON.stringify(columnsDetail))
  columnsTmp.value = columnsDetail.concat(feeCols)
  console.log("columnsTmp:"+JSON.stringify(columnsTmp))
  // console.error("tmp:"+JSON.stringify(tmp))
  await nextTick(()=>{
      detailModal.value?.detail({rec: record, orderArr})
  })
}

function parseFeeDetail(record){
    let feeTipArr = []
    Object.entries(record.feeData).forEach(([key, value])=>{
        feeTipArr.push(`${checkBillStore.feeTypeObj[key]}: ${value.amount}`)
    })
    feeTipStr.value[record.id] = feeTipArr.join("，")
}

function updateMain(id, opType){
  console.error('opType:', opType)
  if(opType === '新建'){
     reset()
  }
  queryList();
}

function updateBillStatus(status){
   queryList();
}

function handleTableChange(pagination, filters, sorter) {
  //分页
  ipagination.value = pagination;
  queryList(sorter);
}

function search(){
  ipagination.value.current = 1
  queryList();
}

function setRowStyle(flag,id) {
  return (record, index,i) => {//executed
    //console.error(JSON.stringify(record))
    let type = record['group']?'executed':'rowBeExec'
    let style = `ant-table-row-selected ${type}`;
    //console.error(style)
    return style;
  }
}

function clearChoice(){
    table.selectedRowKeys = []
    table.selectionRows = []
}

async function queryList(order={"order":"descend", "field":"bill_date"}) {
  // console.error("order",JSON.stringify(order))
  queryParams.value.disabled = true
  loading.value = true
  let param = Object.assign(order, queryParams.value)
  Object.assign(param, _.pick(ipagination.value, ['current', 'pageSize']))
  table.selectionRows = []; table.selectedRowKeys = []
  console.log("param", param);
  dataSource.value = [];
  dataSourceDetail.value = [];
  ipagination.value.total = 0;
  await postAction(url.getCheckBills, _.omit(param,'disabled')).then((res) => {
    if (res && res.success) {
      let {sumUp, detail} = res.data
      dataSourceDetail.value = detail
      //明细费用flat; 有分页,每次量小
      detail.forEach((record)=>{
          record.id_company = parseInt(record.id_company) //改源头，迁移数据历史原因
          for(let key in record.feeData){
              record[key] = record.feeData[key].amount
          }
      })
      dataSource.value = sumUp
      let total = sumUp.find((item)=>!item.group_name)
      ipagination.value.total = parseInt(total.total)
    } else {
      message.error(`查询失败!${res.message}`)
      console.error('错误原因', res.message)
    }
  }).finally(()=>{
      queryParams.value.disabled = false
      loading.value = false
  })
}

function rowSelection() {
  const selectedRowKeys = table.selectedRowKeys
  if(selectable.value) {
    return {
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        table.selectedRowKeys = selectedRowKeys
        table.selectionRows = selectedRows
      }
    };
  }
}
const onColumnsUpdate = (data) =>{
  //很奇怪自动更新了，可能还是指针引用 ，不再需要手动更新
  if(columnConfigKey.value==='checkingBillDetail')
      columnsDetailTmp.value = data
  else
      columnsSummaryTmp.value = data
  console.error("column update:",data)
  console.log("column update!")
}
// 对象形式传递
instance.ctx.changeColumnConfig = changeColumnConfig

onMounted(() => {
  getTemplateConfig()
  autoQuery()
});

</script>

<style scoped>
.ant-table-bordered .ant-table-tbody > tr > td,th{
  padding:4px !important;
}
.ant-popover-inner-content {
  padding:4px !important;
}
.underline {
  font-weight: bold;
  color: red;
}
</style>